<?php

class WeixinController extends Controller {

	private static $_p; // HTTP_RAW_POST_DATA

	public static function get_p()
	{
		return self::$_p;
	}

	// 响应文本输入相关函数
	private static $_arr_main_fn = array(
		'1' => array('fn' => 'sample', 'state' => 1, 'main_content' => '例子',),
	);
	
	private static $_arr_main_fn2 = array(
		'w.' => array('fn' => 'content', 'state' => 0, 'main_content' => '城市信息',),
	);
	// 响应菜单位输入相关函数
	private static $_arr_menu_fn = array(
		'1' => array('fn' => 'sample', 'state' => 1, 'main_content' => '例子',),
		'99' => array('fn' => 'google', 'state' => 0, 'main_content' => '例子',),
	);

	// 使用错误的静态函数时的错误处理。
	public static function __callStatic($name, $arguments)
	{
		$model = $this->load_mem_model();
		$model->mem_state = '';
		// 注意: $name 的值区分大小写
		$this->show_text("Calling object method '$name' "
				. implode(', ', $arguments) . "\n");
	}

	// 使用错误的函数时的错误处理。
	public function __call($name, $arguments)
	{
		$model = $this->load_mem_model();
		$model->mem_state = '';
		// 注意: $name 的值区分大小写
		$this->show_text("Calling object method '$name' "
				. implode(', ', $arguments) . "\n");
	}

	public function init()
	{
		if (isset($_GET['echostr']))
		{// 验证模式,当在微信公众平台开启开发模式时需验证服务器是否配置正确使用
			CWei::valid();
		}
		else
		{
			// CWei::valid();
			self::$_p = CWei::get_post();
			
			$this->{'_input_' . self::$_p['MsgType']}();
		}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Router the loaded model
	 * @throws CHttpException
	 */
	public function load_mem_model($save = FALSE)
	{
		static $model;
		$model === NULL && $model = Member::model()->findByPk(self::$_p['FromUserName']);

		if ($model)
		{
			// 状态只存在10分钟 
			if ($_SERVER['REQUEST_TIME'] - 600 > $model->mem_statetime)
			{
				$model->mem_state = '';
				$model->mem_statetime = $_SERVER['REQUEST_TIME'];
			};
			if ($save)
			{
				$model->mem_statetime = $_SERVER['REQUEST_TIME'];
				$model->save();
			}
			else
			{
				return $model;
			}
		}
		else
		{
			$model = new Member;
			
			$model->attributes = array(
				'mem_username' => self::$_p['FromUserName'],
				'mem_createtime' => self::$_p['CreateTime'],
			);
			
			return $model;
		}
	}

	// 文本类型输入
	private function _input_text()
	{
		self::$_p['key'] = self::$_p['Content'];
		$k_fn = self::$_p['key'];

		$model = $this->load_mem_model();

		if ($k_fn === CWei::MAIN_MEUN)
		{
			$model->mem_state = '';
			$this->output_default();
		}
		elseif ($model->mem_state)
		{// 用户有状态
			$this->_call_state($model->mem_state);
		}
		elseif (isset(self::$_arr_main_fn[$k_fn]))
		{// 用户无状态 回复主页的相关的键;
			$this->_call_fn(self::$_arr_main_fn[$k_fn]);
		}
		elseif ($k = self::_is_pos($k_fn))
		{// 用户无状态 回复主页的相关的键;
			$this->_call_fn(self::$_arr_main_fn2[$k], ltrim($k_fn, $k));
		}
		else
		{// 用户无状态 回复 和 主页不相关的键
			$this->output_default();
		}
	}
	
	private static function _is_pos($key)
	{
		foreach (self::$_arr_main_fn2 as $k => $v)
		{
			if (strpos($key, $k) === 0)
			{
				return $k;
			}
		}
		return false;
	}

	private function _call_fn($arr_fn, $data = false)
	{
		if ($arr_fn['state'])
		{// 如果有状态
			self::_call_state($arr_fn['fn'], $data);
		}
		else
		{
			$fn = '_main_' . $arr_fn['fn'];
			$this->$fn($data);
		}
	}

	private function _call_state($state, $data=false)
	{
		$i = strpos($state, '_');

		if ($i)
		{
			$prefix = substr($state, 0, $i);
			$fn = substr($state, $i + 1);
		}
		else
		{
			$prefix = $state;
			$fn = 'start';
		}

		$sub_controller = ucfirst($prefix) . 'SubController';

		Yii::import("ext.sub_controller.{$sub_controller}");
		
		call_user_func(array($sub_controller, 'init'), $this);
		call_user_func(array($sub_controller, $fn), $data);
		// need php 5.3
		// $sub_controller::init($this);
		// $sub_controller::$fn($data);
	}

	private static function _strstr($haystack, $needle = '_', $before_needle = true)
	{
		if ($before_needle)
		{
			$i = strpos($haystack, $needle);
			if ($i)
			{
				return substr($haystack, 0, $i);
			}
			else
			{
				return $haystack;
			}
		}
		else
		{
			return strstr($haystack, $needle);
		}
	}

	// 事件类型输入
	private function _input_event()
	{
		// Event 	 事件类型，subscribe(订阅)、unsubscribe(取消订阅)、CLICK(自定义菜单点击事件)
		// EventKey 	 事件KEY值，与自定义菜单接口中KEY值对应
		// '' =>  self::$_p['ToUserName'],// '' =>  self::$_p['MsgType'],// '' =>  self::$_p['Event'],// '' =>  self::$_p['EventKey'],
		if (self::$_p['Event'] === 'CLICK')
		{
			self::$_p['key'] = self::$_p['EventKey'];
			$k_fn = self::$_p['key'];

			if (isset(self::$_arr_menu_fn[$k_fn]))
			{// 用户无状态 回复主页的相关的键;
				$this->_call_fn(self::$_arr_menu_fn[$k_fn]);
			}
			else
			{
				$this->output_default();
			}
		}
		elseif (self::$_p['Event'] === 'subscribe')
		{
			$model = $this->load_mem_model();

			if ($model->save())
			{
				$this->_output_subscribe();
			}
			else
			{
				$this->output_err();
			}
		}
		elseif (self::$_p['Event'] === 'unsubscribe')
		{
			$model = $this->load_mem_model();

			if ($model->mem_username)
			{// 用户存在
				$model->delete();
				$this->_output_unsubscribe();
			}
		}
		else
		{
			$this->output_default();
		}
	}
	
	public function show($view, $content = '')
	{
		$this->renderPartial($view, array(
			'toUser' => self::$_p['FromUserName'],
			'fromUser' => self::$_p['ToUserName'],
			'createTime' => self::_get_time(),
			'content' => $content,
		));
	}

	public function show_text($content = '')
	{
		$this->renderPartial('text', array(
			'toUser' => self::$_p['FromUserName'],
			// 'fromUser' => CWei::NAME,
			'fromUser' => self::$_p['ToUserName'],
			'createTime' => self::_get_time(),
			'content' => $content,
		));
	}

	private static function _get_time()
	{
		if ($_SERVER['REQUEST_TIME'] > self::$_p['CreateTime'])
		{
			return $_SERVER['REQUEST_TIME'];
		}
		else
		{
			return self::$_p['CreateTime'];
		}
	}
	/* main start */
	private function _main_content($data)
	{
		$this->show_text("{$data}的信息");
	}
	private function _main_senate()
	{
		$this->show_text('<a href="http://www.google.com">google</a>');
	}
	/* main end */

	private function _main_bind()
	{
		$this->_output_development();
	}
	
	private function _output_subscribe()
	{// 关注成功
		$this->show_text($this->renderPartial('main_subscribe', array(
					'items' => self::$_arr_main_fn,
					'items2' => self::$_arr_main_fn2,
						), true));
	}
	
	private function _output_unsubscribe()
	{// 取消关注成功
		$this->show_text('取消关注成功。');
	}
	
	public function output_default()
	{// 在用户无状态下，默认返回的页面
		$this->show_text($this->renderPartial('main_default', array(
					'items' => self::$_arr_main_fn,
					'items2' => self::$_arr_main_fn2,
						), true));
	}
	
	public function output_err($msg = '')
	{// 错误页面
		$this->show_text("{$msg} 服务器繁忙， 请稍后再试。");
	}
	
	private function _output_development()
	{// 未完成页面
		$this->show_text('此页面未开发');
	}
	
	public function actionIndex()
	{
		$this->load_mem_model(TRUE);
	}

}
